import { defineStore } from 'pinia';
import Cookies from 'js-cookie';
import { Session } from '/@/utils/storage';
import userApi from '/@/api/user';
import { ElMessage } from 'element-plus';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosState => ({
		userInfos: {
			userName: '',
			photo: '',
			time: 0,
			roles: [],
			authBtnList: [],
		},
	}),
	actions: {
		async setUserInfos() {
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo');
			} else {
				await this.getApiUserInfo();
			}
		},
		// 模拟接口数据
		// https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
		async getApiUserInfo() {
			// 模拟数据，请求接口时，记得删除多余代码及对应依赖的引入
			const userName = Cookies.get('userName');
			// 模拟数据
			let defaultRoles: Array<string> = [];
			let defaultAuthBtnList: Array<string> = [];
			// admin 页面权限标识，对应路由 meta.roles，用于控制路由的显示/隐藏
			let adminRoles: Array<string> = [];
			// admin 按钮权限标识
			let adminAuthBtnList: Array<string> = [];
			// test 页面权限标识，对应路由 meta.roles，用于控制路由的显示/隐藏
			let testRoles: Array<string> = [];
			// test 按钮权限标识
			let testAuthBtnList: Array<string> = [];

			if (Session.get('userId')) {
				await userApi
					.userMsg(Session.get('userId'))
					.then((res) => {
						console.log(res.code);
						if (res.code == 0) {
							adminRoles = ['admin'];
							adminAuthBtnList = ['btn.add', 'btn.del', 'btn.edit', 'btn.link'];
							defaultRoles = adminRoles;
							defaultAuthBtnList = adminAuthBtnList;
							// 用户信息模拟数据
							const userInfos = {
								userName: userName,
								photo:
									userName === 'shiwei'
										? 'https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500'
										: 'https://img2.baidu.com/it/u=2370931438,70387529&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
								time: new Date().getTime(),
								roles: defaultRoles,
								authBtnList: defaultAuthBtnList,
							};
							this.userInfos = userInfos;
						}
					})
					.catch((err) => {
						ElMessage.warning(err);
					});
			} else {
				testRoles = ['common'];
				// test 按钮权限标识
				testAuthBtnList = ['btn.add', 'btn.link'];
				defaultRoles = testRoles;
				defaultAuthBtnList = testAuthBtnList;
				// 用户信息模拟数据
				const userInfos = {
					userName: userName,
					photo:
						userName === 'shiwei'
							? 'https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500'
							: 'https://img2.baidu.com/it/u=2370931438,70387529&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
					time: new Date().getTime(),
					roles: defaultRoles,
					authBtnList: defaultAuthBtnList,
				};
				this.userInfos = userInfos;
			}
		},
	},
});
